package com.newworld.dmsapp2.ui.view;

import java.io.File;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.newworld.dmsapp2.R;
import com.newworld.dmsapp2.activity.serviceapply.ChoosephotoActivity;
import com.newworld.dmsapp2.activity.serviceapply.SoundActivity;
import com.newworld.dmsapp2.activity.serviceapply.ViewPagerActivity;
import com.newworld.dmsapp2.fragment.bean.InitPhotoVoiceItemEntity;
import com.newworld.dmsapp2.fragment.bean.InitPhotoVoiceItemEntityServe;
import com.newworld.dmsapp2.util.Config;
import com.newworld.dmsapp2.util.StringUtil;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

public class CustomPhotoVoiceItem extends Fragment implements OnClickListener{
	
	private LayoutInflater mInflater;
	private View customPhotoVoiceItem;
	private ImageView photo1,photo2,voice;
	private TextView voiceTime;
	private BadgeView badgeImage1,badgeImage2,badgeVoice;
	
	private Context context;
	private InitPhotoVoiceItemEntity photoVoiceItem = new InitPhotoVoiceItemEntity();
	private InitPhotoVoiceItemEntityServe photoVoiceItemserve = new InitPhotoVoiceItemEntityServe();
	private boolean reportOrServe;
	private boolean changeViewflag;
	private String photo1RealPath,photo2RealPath,voiceRealPath;
	private String photo1Path = "",photo2Path = "",voicePath = "";
	private String voiceTimeStr;
	private Uri imageUri;
	
	public CustomPhotoVoiceItem(Context context) {
		super();
		// TODO Auto-generated constructor stub
	}

	//获取报修节点信息
	public LinearLayout getCustomPhotoVoiceItem(Context context,InitPhotoVoiceItemEntity photoVoiceItem,Boolean reportOrServe) {
		// TODO Auto-generated constructor stub
		this.context = context;
		this.photoVoiceItem = photoVoiceItem;
		this.reportOrServe = reportOrServe;
		changeViewflag = photoVoiceItem.isChangeView();
		
		mInflater = LayoutInflater.from(context);
		customPhotoVoiceItem = mInflater.inflate(R.layout.view_custom_photovoiceitem, null);//报修节点
		initData();
		initView(customPhotoVoiceItem);
		initEvent();
		return (LinearLayout) customPhotoVoiceItem;
	}
	//获取维修节点信息
	public LinearLayout getCustomPhotoVoiceItem(Context context,InitPhotoVoiceItemEntityServe photoVoiceItem,Boolean reportOrServe) {
		// TODO Auto-generated constructor stub
		this.context = context;
		this.photoVoiceItemserve = photoVoiceItem;
		this.reportOrServe = reportOrServe;
		changeViewflag = photoVoiceItem.isChangeViewS();
		
		mInflater = LayoutInflater.from(context);
		customPhotoVoiceItem = mInflater.inflate(R.layout.view_custom_photovoiceitemserve, null);//维修节点
		initData();
		initView(customPhotoVoiceItem);
		initEvent();
		return (LinearLayout) customPhotoVoiceItem;
	}
	
	private void initData(){
		if(!reportOrServe){
			if(StringUtil.isStringAvailable(photoVoiceItem.getImagePath1())){
				photo1Path = photoVoiceItem.getImagePath1();
				photo1RealPath = Config.IMAGE_PATH + photo1Path;
			}
			if(StringUtil.isStringAvailable(photoVoiceItem.getImagePath2())){
				photo2Path = photoVoiceItem.getImagePath2();
				photo2RealPath = Config.IMAGE_PATH + photo2Path;
			}
			if(StringUtil.isStringAvailable(photoVoiceItem.getVoicePath())){
				voicePath = photoVoiceItem.getVoicePath();
				voiceRealPath =  Config.VOICE_PATH + voicePath;
			}
			if(StringUtil.isStringAvailable(photoVoiceItem.getVoiceTime())){
				voiceTimeStr = photoVoiceItem.getVoiceTime();
			}
		}
		else{
			if(StringUtil.isStringAvailable(photoVoiceItemserve.getImagePathS1())){
				photo1Path = photoVoiceItemserve.getImagePathS1();
				photo1RealPath = Config.IMAGE_PATH + photo1Path;
			}
			if(StringUtil.isStringAvailable(photoVoiceItemserve.getImagePathS2())){
				photo2Path = photoVoiceItemserve.getImagePathS2();
				photo2RealPath = Config.IMAGE_PATH + photo2Path;
			}
			if(StringUtil.isStringAvailable(photoVoiceItemserve.getVoicePathS())){
				voicePath = photoVoiceItemserve.getVoicePathS();
				voiceRealPath =  Config.VOICE_PATH + voicePath;
			}
			if(StringUtil.isStringAvailable(photoVoiceItemserve.getVoiceTimeS())){
				voiceTimeStr = photoVoiceItemserve.getVoiceTimeS();
			}
		}
	}
	
	private void initView(View customTextItem) {
		if(!reportOrServe){
			photo1 = (ImageView) customPhotoVoiceItem.findViewById(R.id.custom_photovoice_photo1);
			photo2 = (ImageView) customPhotoVoiceItem.findViewById(R.id.custom_photovoice_photo2);
			voice = (ImageView) customPhotoVoiceItem.findViewById(R.id.custom_photovoice_voice);
			voiceTime = (TextView) customTextItem.findViewById(R.id.custom_photovoice_voicetime);
		}else{
			photo1 = (ImageView) customPhotoVoiceItem.findViewById(R.id.accomplish_solve_imageView1);
			photo2 = (ImageView) customPhotoVoiceItem.findViewById(R.id.accomplish_solve_imageView2);
			voice = (ImageView) customPhotoVoiceItem.findViewById(R.id.accomplish_solve_voiceView);
			voiceTime = (TextView) customTextItem.findViewById(R.id.accomplish_solve_recordtime);
		}
		
		badgeImage1 = new BadgeView(context, photo1);
		badgeImage2 = new BadgeView(context, photo2);
		badgeVoice = new BadgeView(context, voice);
		badgeImage1.hide();
		badgeImage2.hide();
		badgeVoice.hide();
		if (StringUtil.isStringAvailable(photo1Path)) {
			photo1.setVisibility(View.VISIBLE);
			ImageLoader.getInstance().displayImage(
					"file://" + photo1RealPath,
					photo1, options);
		} else {
			photo2.setVisibility(View.INVISIBLE);
		}
		if (StringUtil.isStringAvailable(photo2Path)) {
			photo1.setVisibility(View.VISIBLE);
			ImageLoader.getInstance().displayImage(
					"file://" + photo2RealPath,
					photo2, options);
		}else {
			photo2.setVisibility(View.INVISIBLE);
		}
		if (StringUtil.isStringAvailable(voicePath)) {
			voice.setVisibility(View.VISIBLE);
			ImageLoader.getInstance().displayImage(
					"file://" + voiceRealPath,
					voice, options);
		}else {
			voice.setVisibility(View.INVISIBLE);
			voiceTime.setVisibility(View.INVISIBLE);
		}
		if (StringUtil.isStringAvailable(voiceTimeStr)) {
			photo1.setVisibility(View.VISIBLE);
			ImageLoader.getInstance().displayImage(
					"file://" + voiceRealPath,
					voice, options);
		}else {
			voiceTime.setVisibility(View.INVISIBLE);
		}
		if(changeViewflag){
			initBadgeView(badgeImage1);
			initBadgeView(badgeImage2);
			initBadgeView(badgeVoice);
		}
	}
	
	/**
	 * 初始化右上角删除标志
	 * @param view
	 */
	private void initBadgeView(BadgeView view){
		view.setText("  ");
		view.setTextSize(12);
		view.setBackgroundResource(R.drawable.badge_view);
		view.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
		view.setBadgeMargin(0, 0);
		view.toggle();
	}
	
	private void initEvent(){
		if(StringUtil.isStringAvailable(photoVoiceItem.getImagePath1())){
			photo1.setVisibility(View.VISIBLE);
			photo1.setOnClickListener(this);
		
			if(changeViewflag){
				badgeImage1.show();
				badgeImage1.setOnClickListener(badgeImage1Listener);
			}
		}
		if(StringUtil.isStringAvailable(photoVoiceItem.getImagePath2())){
			photo2.setVisibility(View.VISIBLE);
			photo2.setOnClickListener(this);
		
			if(changeViewflag){
				badgeImage2.show();
				badgeImage2.setOnClickListener(badgeImage2Listener);
			}
		}
		if(StringUtil.isStringAvailable(photoVoiceItem.getVoicePath())){
			voice.setVisibility(View.VISIBLE);
			voice.setOnClickListener(this);
			voiceTime.setVisibility(View.VISIBLE);
			voiceTime.setText(voiceTimeStr + "");
			if(changeViewflag){
				badgeVoice.show();
				badgeVoice.setOnClickListener(badgeVoiceListener);
			}
		}
		
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.custom_photovoice_photo1:
			photoClickEvent(1);
			break;
		case R.id.custom_photovoice_photo2:
			photoClickEvent(2);
			break;
		case R.id.custom_photovoice_voice:
			VoiceClickEvent();
			break;
		default:
			break;
		}
		
	}
	
	/**
	 * 图片点击事件
	 * @param position
	 * @param photoRealPath
	 * @param intentPhotoRealPath
	 * @return
	 */
	private void photoClickEvent(final int position) {
		if (changeViewflag) {
			if (photo1Path.equals("")) {
				final Dialog dlg = new Dialog(context, R.style.ActionSheet);
				LayoutInflater inflater = (LayoutInflater) context
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				LinearLayout layout = (LinearLayout) inflater.inflate(
						R.layout.activity_writepaper_dialog, null);
				final int cFullFillWidth = 10000;
				layout.setMinimumWidth(cFullFillWidth);

				TextView mContent1 = (TextView) layout
						.findViewById(R.id.tv_content1);
				TextView mContent2 = (TextView) layout
						.findViewById(R.id.tv_content2);
				TextView mCancel = (TextView) layout
						.findViewById(R.id.tv_cancel);
				// 拍摄选择照片
				mContent1.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						String temName = DateFormat.format("yyMMdd_hhmmss",
								System.currentTimeMillis())
								+ "_"
								+ (Math.random() * 100) + ".jpg";
						File file = null;
						if(position == 1){
							photo1Path = temName;
							photo1RealPath = Config.IMAGE_PATH+ temName;
							file = new File(photo1RealPath);
						}else if(position == 2){
							photo2Path = temName;
							photo2RealPath = Config.IMAGE_PATH+ temName;
							file = new File(photo2RealPath);
						}
						if (file.exists()) {
							file.delete();
						}
						imageUri = Uri.fromFile(file);
						Intent intent = new Intent(
								MediaStore.ACTION_IMAGE_CAPTURE);

						intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
						if(position == 1){
							((FragmentActivity) context).startActivityForResult(
									intent, 1);
						}else if(position == 2){
							((FragmentActivity) context).startActivityForResult(
									intent, 3);
						}
						dlg.dismiss();
					}
				});
				// 从相册中选择照片
				mContent2.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Intent choosePictureIntent = new Intent(
								Intent.ACTION_PICK,
								android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
						choosePictureIntent.setType("image/jpeg");
						if(position == 1){
							((FragmentActivity) context).startActivityForResult(
									choosePictureIntent, 2);
						}else if(position == 2){
							((FragmentActivity) context).startActivityForResult(
									choosePictureIntent, 4);
						}
						
						dlg.dismiss();
					}
				});

				mCancel.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						dlg.dismiss();
					}
				});

				Window w = dlg.getWindow();
				WindowManager.LayoutParams lp = w.getAttributes();
				lp.x = 0;
				final int cMakeBottom = -1000;
				lp.y = cMakeBottom;
				lp.gravity = Gravity.BOTTOM;
				dlg.onWindowAttributesChanged(lp);
				dlg.setCanceledOnTouchOutside(false);
				dlg.setContentView(layout);
				dlg.show();
			} else {
				Intent intent2 = new Intent(context, ViewPagerActivity.class);
				if(position == 1){
					intent2.putExtra("image1", "file://" + photo1RealPath);
					intent2.putExtra("image2", "file://" + photo2RealPath);
				}else{
					intent2.putExtra("image1", "file://" + photo2RealPath);
					intent2.putExtra("image2", "file://" + photo1RealPath);
				}
				((FragmentActivity) context).startActivity(intent2);
			}
		} else {
			Intent intent2 = new Intent(context, ViewPagerActivity.class);
			if(position == 1){
				intent2.putExtra("image1", "file://" + photo1RealPath);
				intent2.putExtra("image2", "file://" + photo2RealPath);
			}else{
				intent2.putExtra("image1", "file://" + photo2RealPath);
				intent2.putExtra("image2", "file://" + photo1RealPath);
			}
			((FragmentActivity) context).startActivity(intent2);
		}
	}
	
	/**
	 * 语音图标点击事件
	 */
	private void VoiceClickEvent(){
		if(changeViewflag){
			if (voicePath.equals("")) {
				File parent2 = new File(Config.VOICE_PATH);
				if (!parent2.exists()) {
					parent2.mkdirs();
				}
				Intent intent4 = new Intent(
						context,
						SoundActivity.class);
				((FragmentActivity) context).startActivityForResult(intent4, 7);
			} else {
				File clickfile0 = new File(Config.VOICE_PATH
						+ voicePath);
				Intent a = new Intent();
				a.setAction(Intent.ACTION_VIEW);

				a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				a.putExtra("oneshot", 0);
				a.putExtra("configchange", 0);

				a.setDataAndType(Uri.parse("file:" + clickfile0.getPath()),
						"audio/*");
				((FragmentActivity) context).startActivity(a);
			}
		}else{
			File clickfile1 = new File(Config.VOICE_PATH + voicePath);
			Intent it1 = new Intent();
			it1.setAction(Intent.ACTION_VIEW);
			it1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			it1.putExtra("oneshot", 0);
			it1.putExtra("configchange", 0);
			it1.setDataAndType(Uri.parse("file:" + clickfile1.getPath()),
					"audio/*");
			((FragmentActivity) context).startActivity(it1);
		}
	}
	
	 
	 /**
	 * 图片1右上角删除图标的监听 badgeImage1Listener
	 */
	OnClickListener badgeImage1Listener = new OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			photo1RealPath = photo2RealPath;
			photo1Path = photo2Path;
			photo2Path = "";
			photo2RealPath = "";

			if (photo1Path.equals("")) {
				badgeImage1.hide();
				ImageLoader.getInstance().displayImage(
						null, photo1, options);

				photo2.setVisibility(View.INVISIBLE);
			} else {
				badgeImage2.hide();
				ImageLoader.getInstance().displayImage(
						"file://" + Config.IMAGE_PATH +photo1Path,
								photo1, options);
				ImageLoader.getInstance().displayImage(
						null, photo2, options);
			}
		}
	};
	
    /**
     *图片2右上角删除图标的监听 badgeImage2Listener 
     */
    OnClickListener badgeImage2Listener = new OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			photo2Path = "";
			photo2RealPath = "";
			badgeImage2.hide();
			ImageLoader.getInstance().displayImage(null, photo2,
					options);
		}
	};
	
	/**
	 * 语音右上角删除图标的监听 badgeVoiceListener 
	 */
	OnClickListener badgeVoiceListener = new OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			badgeVoice.hide();
			voicePath = "";
			voiceTime.setVisibility(View.INVISIBLE);
			voice.setBackground(getResources().getDrawable(
					R.drawable.btn_voice_taken));
		}
	};
	
	public static final DisplayImageOptions options = new DisplayImageOptions.Builder()
	.cacheInMemory(false) // 设置下载的图片是否缓存在内存中
	.cacheOnDisk(false).bitmapConfig(Bitmap.Config.RGB_565) // 设置下载的图片是否缓存在SD卡中
	.displayer(new RoundedBitmapDisplayer(10)) // 设置成圆角图片
	.build();

	
	@SuppressLint("NewApi")
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK && requestCode == 1) {
			Bundle b = new Bundle();
			b.putString("imagePath", photo1RealPath);
			Intent intent = new Intent(context,
					ChoosephotoActivity.class);
			intent.putExtras(b);
			startActivityForResult(intent, 5);
		} else if (resultCode == Activity.RESULT_OK && requestCode == 2) {
			Bundle bundle = new Bundle();
			Uri uri = data.getData();

			String[] filePathColumn = { MediaStore.Images.Media.DATA };
			Log.e("picture", uri.toString());
			Cursor cursor = context.getContentResolver().query(uri, filePathColumn,
					null, null, null);
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			photo1RealPath = cursor.getString(columnIndex);
			cursor.close();
			bundle.putString("imagePath", photo1RealPath);
			Intent intent = new Intent(context,
					ChoosephotoActivity.class);
			intent.putExtras(bundle);
			startActivityForResult(intent, 5);
		}

		else if (resultCode == Activity.RESULT_OK && requestCode == 3) {
			Bundle b1 = new Bundle();
			b1.putString("imagePath", photo2RealPath);
			Intent intent1 = new Intent(context,
					ChoosephotoActivity.class);
			intent1.putExtras(b1);
			startActivityForResult(intent1, 6);
		} else if (resultCode == Activity.RESULT_OK && requestCode == 4) {
			Bundle bundle = new Bundle();
			Uri uri = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };
			Log.e("picture", uri.toString());
			Cursor cursor = context.getContentResolver().query(uri, filePathColumn,
					null, null, null);
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			photo2RealPath = cursor.getString(columnIndex);
			cursor.close();
			bundle.putString("imagePath", photo2RealPath);
			Intent intent = new Intent(context,
					ChoosephotoActivity.class);
			intent.putExtras(bundle);
			startActivityForResult(intent, 6);
		} else if (resultCode == Activity.RESULT_OK && requestCode == 5) {
			photo1Path = data.getStringExtra("imagePath");
			photo1RealPath = Config.IMAGE_PATH + photo1Path;
		} else if (resultCode == Activity.RESULT_OK && requestCode == 6) {
			photo2Path = data.getStringExtra("imagePath");
			photo2RealPath = Config.IMAGE_PATH + photo2Path;
		} else if (resultCode == Activity.RESULT_OK && requestCode == 7) {
			voicePath = data.getStringExtra("voiceName");
			voiceTimeStr = data.getIntExtra("voiceTime", 0)+"'";
		}
		if (!photo1Path.equals("")) {
			badgeImage1.show();
			badgeImage1.setOnClickListener(badgeImage1Listener);
			ImageLoader.getInstance().displayImage(
					"file://" + Config.IMAGE_PATH + photo1Path,
					photo1, options);
			getResources().getDrawable(
					R.drawable.defect_compose_pic_add_highlighted);
			photo2.setVisibility(View.VISIBLE);
		}
		if (!photo2Path.equals("")) {
			badgeImage1.show();
			badgeImage1.setOnClickListener(badgeImage2Listener);
			ImageLoader.getInstance().displayImage(
					"file://" + Config.IMAGE_PATH + photo1Path,
					photo2, options);
		}

		if (!voicePath.equals("")) {
			voice.setBackground(getResources().getDrawable(
					R.drawable.record_voice));
			initBadgeView(badgeVoice);

			voiceTime.setVisibility(View.VISIBLE);
			voiceTime.setText(voiceTimeStr + "'");
		}
	}
}
